from django.shortcuts import render
from django.shortcuts import render
from django.db import models
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.views.decorators.csrf import csrf_exempt
#from VIS.models import Img
from tingchechang import urls
from tingchechang import settings
import json
import os
import datetime
import cv2
from shibie.plate_recognition import plate_recodnition
from paddle1.chexingshibie import scanALL
from Car_Port.updata_db import *  ############################################
#from shibie.plate_recognition import plate_recodnition2
#import shibie
import shutil
from regional_identification.main import QueryRegionByCarNumPrefix
from car_recognition.Recognition import loadModel
from car_recognition.Recognition import getModel
from baiduAPIjiashixingweijiance.jiashixingweijiance import weixianjiashixingwei
from baiduAPIchesunshibie.chesunshibie import recognizer
import cv2
from parking_database.data2logic import *
from parking_database.query import *
from parking_database.appointment_record import query_appointment_by_plate1
from parking_database.insert import query_is_carinpark_by_plate
from parking_database.insert import *

# Create your views here.


color = [{'id':0,'color':'orangered'},{'id':1,'color':'orangered'},{'id':2,'color':'orangered'},{'id':3,'color':'orangered'},{'id':4,'color':'orangered'},
        {'id':5,'color':'orangered'},{'id':6,'color':'orangered'},{'id':7,'color':'orangered'},{'id':8,'color':'orangered'},{'id':9,'color':'orangered'},
        {'id':10,'color':'orangered'},{'id':11,'color':'orangered'},{'id':12,'color':'orangered'},{'id':13,'color':'orangered'},{'id':14,'color':'orangered'},
        {'id':15,'color':'orangered'},{'id':16,'color':'orangered'},{'id':17,'color':'orangered'},{'id':18,'color':'orangered'},{'id':19,'color':'orangered'},
        {'id':20,'color':'orangered'},{'id':21,'color':'orangered'},{'id':22,'color':'orangered'},{'id':23,'color':'orangered'},{'id':24,'color':'orangered'},]

carlist1 = [{'id': 0, 'chepai': '', 'chexing': ''}, {'id': 1, 'chepai': '渝H11557', 'chexing': '黑色丰田佳美'}
    , {'id': 2, 'chepai': '浙J1573Q', 'chexing': '蓝色大众高尔夫(Golf)'}, {'id': 3, 'chepai': '辽AH5U61', 'chexing': '白色奔腾X80'}
    , {'id': 4, 'chepai': '苏DFF458', 'chexing': '黄色法拉利458'}, {'id': 5, 'chepai': '', 'chexing': ''}
    , {'id': 6, 'chepai': '苏DS0000', 'chexing': '黑色大众捷达'}
    , {'id': 7, 'chepai': '云ATD239', 'chexing': '黑色日产颐达'}, {'id': 8, 'chepai': '鲁BD8J53', 'chexing': '黑色大众帕萨特(Passat)(领驭)'}
       ,{'id':9,'chepai':'鄂Asb253','chexing':'宝马'},{'id':10,'chepai':'鄂Asb254','chexing':'奔驰'},{'id':11,'chepai':'鄂Asb255','chexing':'布加迪威龙'}
       ,{'id':12,'chepai':'','chexing':''},{'id':13,'chepai':'鄂Asb254','chexing':'奔驰'},{'id':14,'chepai':'鄂Asb255','chexing':'布加迪威龙'}
       ,{'id':15,'chepai':'鄂Asb256','chexing':'柯尼塞格'},{'id':16,'chepai':'','chexing':''},{'id':17,'chepai':'鄂Asb256','chexing':'柯尼塞格'}
       ,{'id':18,'chepai':'','chexing':''},{'id':19,'chepai':'鄂Asb256','chexing':'柯尼塞格'},{'id':20,'chepai':'鄂Asb256','chexing':'柯尼塞格'}
       ,{'id':21,'chepai':'鄂Asb256','chexing':'柯尼塞格'},{'id':22,'chepai':'','chexing':''},{'id':23,'chepai':'鄂Asb256','chexing':'柯尼塞格'}
    ,{'id':24,'chepai':'鄂Asb256','chexing':'柯尼塞格'}]
meta,model = loadModel()
carlist = scanALL(meta,model)
for a in carlist:
    print(a,"for")
    if a['chepai']!="":
        if updateSelect(a['chepai']):
            inport(a['chepai'])




realpassword = 'Ehomeyyds'


def chaxun(request):
    chepai = request.POST.get('chaxun',None)
    location = ''
    img = ''

    print(chepai)
    for i in range(0,25):
        if chepai == carlist[i]['chepai']:
            location = '您的车辆'+chepai+'所在停车位ID为:' + str(carlist[i]['id'])
            if i<10:
                img = '/static/carimg/0' + str(carlist[i]['id'])+'.jpg'
            else:
                img = '/static/carimg/' + str(carlist[i]['id'])+'.jpg'


    return render(request,"chaxun.html",{'id':location,'realid':img})


def picChanger(img,chepai,chexing):
    data = query_all_parking_space()
    print(data)

    for item in data:
        if item['车牌']=='' or None:
            if item['车位']<10:
                true_name = '0'+str(item['车位'])

            else:true_name= str(item['车位'])
            print(true_name)
            cv2.imwrite("static/carimg/"+true_name + '.jpg', img)
            input_enter_info(item['车位'],chepai,chexing)
            break


def carouter(plate):
    img=cv2.imread("static/rubish.jpg")
    data= query_all_parking_space()
    for item in data:
        if item['车牌']==plate:
            if item['车位']<10:
                true_name = '0'+str(item['车位'])

            else:true_name= str(item['车位'])
            cv2.imwrite("static/carimg/"+true_name+'.jpg',img)
            input_enter_info(item['车位'],'','')
            break










def index(request):
    return render(request, "index.html")

def first(request):
    return render(request,"first.html")

def mima(request):
    return render(request,"mima.html")

def chesun(request):
    return render(request,"chesun.html")

def yonghu(request):
    return render(request,"yonghu.html")

def weixian(request):
    return render(request,"weixian.html")

def yuyue(request):
    return render(request,"yuyue.html")






def yuyuechaxun(request):
    chepai = request.POST.get('yuyuechaxun',None)
    str = query_plate(chepai)


    realresult = '您的查询结果为: '+str
    return render(request,"yuyue.html",{'result':realresult})

def xinjianyuyue(request):
    chepai = request.POST.get('yuyuechepai',None)
    shichang = int(request.POST.get('yuyueshichang',None))

    add_app(chepai,shichang,0)
    str = "预约已提交"
    return render(request,'yuyue.html',{'tijiao':str})


def indexupload(request):
    print(request.POST.get('3',None))


    return render(request,"index.html",{'detail':color,'cardetail':carlist})

def tijiaomima(request):
    password = request.POST.get('password',None)
    remind = '密码输入错误请重新输入密码！！！'
    if password == realpassword:
        return render(request,"index.html")
    else:
        return render(request,"mima.html",{'remind':remind})

def weixianpic_upload(request):
    if request.method == "POST":
        dirpath = "static/images"
        shutil.rmtree(dirpath)
        os.mkdir(dirpath)
        error = ""

        fp = request.FILES.get("file")
        # fp 获取到的上传文件对象
        #img = cv2.imread(fp)
        #cv2.imshow('aaa',img)
        if fp:
            x = fp.name
            suffix = os.path.splitext(x)[1]
            if suffix == '.png' or suffix == '.jpg' or suffix == '.jpeg' or suffix == '.PNG' or suffix == '.JPG' or suffix == '.JPEG':
                path = default_storage.save("../images/" + fp.name,
                                            ContentFile(fp.read()))  # 上传文件本地保存路径， image是static文件夹下专门存放图片的文件夹
                # temp_file = os.path.join(settings.STATICFILES_DIRS[0],path)

                data = '/static/images/' + fp.name
                data2 = 'static/images/' + fp.name
                img = cv2.imread(data2)
                warning = weixianjiashixingwei(data2)
                print(data)
                print(warning)
                #cv2.imshow('aaa',img)
                #cv2.waitKey(0)
                #chepai = plate_recodnition(img)
                #chepai2 = plate_recodnition(img)
                remind = ''



            else:
                data = ''
                remind = '图片格式不正确，请重新输入'
                chepai2 = ''
                chexing = ' '
        else:
            data = ''
            remind = '请先选择图片'
            chepai2 = ''
            chexing = ' '

    return render(request,"weixian.html",{'weixianimg':data,'warning':warning})




def chesunpic_upload(request):

    if request.method == "POST":
        dirpath = "static/images"
        shutil.rmtree(dirpath)
        os.mkdir(dirpath)
        error = ""

        fp = request.FILES.get("file")
        # fp 获取到的上传文件对象
        #img = cv2.imread(fp)
        #cv2.imshow('aaa',img)
        if fp:
            x = fp.name
            suffix = os.path.splitext(x)[1]
            if suffix == '.png' or suffix == '.jpg' or suffix == '.jpeg' or suffix == '.PNG' or suffix == '.JPG' or suffix == '.JPEG':
                path = default_storage.save("../images/" + fp.name,
                                            ContentFile(fp.read()))  # 上传文件本地保存路径， image是static文件夹下专门存放图片的文件夹
                # temp_file = os.path.join(settings.STATICFILES_DIRS[0],path)

                data = '/static/images/' + fp.name
                data2 = 'static/images/' + fp.name
                #img = cv2.imread(data2)


                str = recognizer.detect(data2)
                print(str)
                #cv2.imshow('aaa',img)
                #cv2.waitKey(0)
                #chepai = plate_recodnition(img)
                #chepai2 = plate_recodnition(img)
                #remind = ''



            else:
                data = ''
                str = ''
                #remind = '图片格式不正确，请重新输入'
                chepai2 = ''
                chexing = ' '
        else:
            data = ''
            str = ''
            #remind = '请先选择图片'
            chepai2 = ''
            chexing = ' '


    return render(request,"chesun.html",{'chesunimg':data,'result':str})


def shuaxin(request):
    global carlist
    carlist = query_scanall_parking_space()
    suggust_1 = 100
    id_1 = ''
    suggust_2 = 110
    id_2 = ''
    for i in range(0, 25):
        if carlist[i]['chepai'] == '':
            color[i]['color'] = 'lawngreen'
            temp1 = ((carlist[i]['id']) // 5) + ((carlist[i]['id']) % 5)
            if temp1 < suggust_1:
                suggust_1 = temp1
                id_1 = carlist[i]['id']

            temp2 = ((24 - carlist[i]['id']) // 5) + ((24 - carlist[i]['id']) % 5)
            if temp2 < suggust_2:
                suggust_2 = temp2
                id_2 = carlist[i]['id']

        else:
            color[i]['color'] = 'orangered'
    print('sug1', suggust_1, id_1)
    print('sug2', suggust_2, id_2)
    return render(request,"index.html",{'sug1':id_1,'sug2':id_2,'detail':color,'cardetail':json.dumps(carlist)})

def shibiepic_upload(request):
    if request.method == "POST":
        dirpath = "static/images"
        shutil.rmtree(dirpath)
        os.mkdir(dirpath)
        error = ""

        fp = request.FILES.get("file")
        # fp 获取到的上传文件对象
        #img = cv2.imread(fp)
        #cv2.imshow('aaa',img)
        if fp:
            x = fp.name
            suffix = os.path.splitext(x)[1]
            if suffix == '.png' or suffix == '.jpg' or suffix == '.jpeg' or suffix == '.PNG' or suffix == '.JPG' or suffix == '.JPEG':
                path = default_storage.save("../images/" + fp.name,
                                            ContentFile(fp.read()))  # 上传文件本地保存路径， image是static文件夹下专门存放图片的文件夹
                # temp_file = os.path.join(settings.STATICFILES_DIRS[0],path)

                data = '/static/images/' + fp.name
                data2 = 'static/images/' + fp.name
                img = cv2.imread(data2)



                print(data)

                #cv2.imshow('aaa',img)
                #cv2.waitKey(0)
                #chepai = plate_recodnition(img)
                chepai2 = plate_recodnition(img)


                if chepai2 != '':
                    if updateSelect(chepai2):##True in False out 这里是入库
                        if 25-query_carinpark_count()-query_appointment_count()>0:
                            inport(chepai2)
                            chemodel = getModel(data2,meta,model)
                            picChanger(img,chepai2,chemodel)
                            yuyue = app_acomplete(chepai2)
                            region = chepai2[0] + chepai2[1]
                            result = QueryRegionByCarNumPrefix(region)
                            chepai2 = '车牌号是：  '+chepai2+'    属于：  '+result+'   '+yuyue +'入库'
                            chexing = '车型： ' + chemodel

                        elif query_appointment_by_plate(chepai2):
                            chemodel = getModel(data2, meta, model)
                            picChanger(img,chepai2,chemodel)
                            app_acomplete(chepai2)
                            inport(chepai2)
                            region = chepai2[0] + chepai2[1]
                            result = QueryRegionByCarNumPrefix(region)
                            chepai2 = '车牌号是：  ' + chepai2 + '    属于：  ' + result+'  预约车入库'
                            chexing = '车型： ' + chemodel
                        else:
                            chepai2 = '车位已满！！！'
                            chexing = ''
                    else:##出库
                        time = export(chepai2)
                        temp1 = time['天数']
                        temp2 = time['小时']
                        temp3 = time['分钟']
                        ##换图片
                        carouter(chepai2)
                        region = chepai2[0]+chepai2[1]
                        result = QueryRegionByCarNumPrefix(region)
                        chepai2 = '车牌号是：  '+chepai2+'   属于：  '+result+'  出库'
                        chexing = '车型： ' + getModel(data2,meta,model)+'  时长：'+str(temp1)+'天'+str(temp2)+'小时'


                    #更换图片
                #
                #     if 25-query_carinpark_count()-query_appointment_count()>0:
                #
                #         picChanger(img)
                #         app_acomplete(chepai2)
                #         updata_data(chepai2)
                #
                #         region = chepai2[0]+chepai2[1]
                #         result = QueryRegionByCarNumPrefix(region)
                #         chepai2 = '车牌号是：  '+chepai2+'    属于：  '+result
                #         chexing = '车型： ' + getModel(data2,meta,model)
                #
                #     elif query_appointment_by_plate(chepai2):
                #         picChanger(img)
                #         app_acomplete(chepai2)
                #         updata_data(chepai2)
                #
                #         region = chepai2[0] + chepai2[1]
                #         result = QueryRegionByCarNumPrefix(region)
                #         chepai2 = '车牌号是：  ' + chepai2 + '    属于：  ' + result
                #         chexing = '车型： ' + getModel(data2, meta, model)
                #     elif query_is_carinpark_by_plate(chepai2):
                #         updata_data(chepai2)
                #         region = chepai2[0] + chepai2[1]
                #         result = QueryRegionByCarNumPrefix(region)
                #         chepai2 = '车牌号是：  ' + chepai2 + '    属于：  ' + result
                #         chexing = '车型： ' + getModel(data2, meta, model)
                #
                #
                #     else:
                #         chepai2 = '车位已满！！！'
                #         chexing = ''
                # else:
                #     chepai2 = '未识别!!!'
                #     chexing = ' '
                print(chepai2)
                chepai1='车牌号是：'
                # for step,str in enumerate(chepai):
                #     chepai1+=str

                print(data)
                #list1.clear()
                remind = ''
                #os.remove("D:/pycharmcode/web/static/images/"+fp.name)
            else:
                data = ''
                remind = '图片格式不正确，请重新输入'
                chepai2 = ''
                chexing = ' '
        else:
            data = ''
            remind = '请先选择图片'
            chepai2 = ''
            chexing = ' '
            #list1.clear()
        #list1.append(data)

        suggust_1 = 100
        id_1 = ''
        suggust_2 = 110
        id_2 = ''
        for i in range(0,25):
            if carlist[i]['chepai'] == '':
                color[i]['color'] = 'lawngreen'
                temp1 = ((carlist[i]['id']) // 5) + ((carlist[i]['id']) % 5)
                if temp1 < suggust_1:
                    suggust_1 = temp1
                    id_1 = carlist[i]['id']


                temp2 = ((24-carlist[i]['id']) // 5) + ((24-carlist[i]['id']) % 5)
                if temp2 < suggust_2:
                    suggust_2 = temp2
                    id_2 = carlist[i]['id']
            else:
                color[i]['color'] = 'orangered'
        print('sug1' ,suggust_1,id_1)
        print('sug2' ,suggust_2,id_2)

        print(carlist)
        print(color)

    return render(request, "index.html",{
        'imgname':data,'remind':remind,'chepai':chepai2,'detail':color,'cardetail':json.dumps(carlist)
        ,'sug1':id_1,'sug2':id_2,'chexing':chexing
    })  # 重定向到首页